﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;

namespace AugustSql
{
    internal class TableInfor
    {
        private string primaryKey;
        public TableInfor(string primaryKey, [CallerMemberName] string tablename = "")
        {
            this.primaryKey = primaryKey;
            this.TableName = tablename;

            Colums = new List<ColumAttribute>()
            {
                new ColumAttribute()
                {
                    Name=primaryKey,
                    AllowNull=false,
                    Type = SqlValueType.BIGINT,
                    IsPrimaryKey=true,
                    HasDefaultValue=true,
                    AutoIncrement=true,
                    SetLength=true,
                    Length = 20
                }
            };
        }
        public string TableName
        {
            get;
            set;
        }

        List<ColumAttribute> Colums;
        public void AddColum(ColumAttribute colum)
        {
            if (Colums.Select(c => c.Name).Where(name => name == colum.Name).Count() > 0)
                throw new Exception("已经存在了相同的列名称！");
            else
                Colums.Add(colum);
        }

        public string CreatTable()
        {
            StringBuilder sb = new StringBuilder();
            sb.Append($"CREATE TABLE `{TableName}` (");
            sb.Append(CreatColumInfo());
            sb.Append(CreatPrimaryKeyCommand());
            sb.Append(") COLLATE='utf8_general_ci';");
            return sb.ToString();
        }
        internal string CreatColumInfo()
        {
            StringBuilder sb = new StringBuilder();
            foreach (var item in Colums)
            {
                sb.Append(item.CreatInfo());
            }
            return sb.ToString();
        }
        internal string CreatPrimaryKeyCommand()
        {
            if (string.IsNullOrEmpty(primaryKey))
                throw new Exception("You must set a PrimaryKey");
            return $"PRIMARY KEY (`{primaryKey}`)";
        }

    }
}
